package org.example.controller;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.annotation.RepeatSubmit;
import org.example.constant.RedisKey;
import org.example.controller.request.ConfirmOrderRequest;
import org.example.controller.request.ProductOrderPageRequest;
import org.example.enums.BizCodeEnum;
import org.example.enums.JsonCodeEnum;
import org.example.enums.ProductOrderEnum;
import org.example.interceptor.LoginInterceptor;
import org.example.service.ProductOrderService;
import org.example.util.CommonUtil;
import org.example.util.JsonData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 谢超
 * @since 2024-03-22
 */
@RestController
@Slf4j
@RequestMapping("/api/product_order/v1")
public class ProductOrderController {

    @Resource
    private ProductOrderService productOrderService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 分页列表
     * @param pageRequest
     * @return
     */
    @PostMapping("page")
    @RepeatSubmit(limitType = RepeatSubmit.Type.PARAM)
    public JsonData page(@RequestBody ProductOrderPageRequest pageRequest){
        Map<String, Object> pageResult = productOrderService.page(pageRequest);
        return JsonData.buildSuccess(pageResult);
    }

    /**
     * 下单前获取令牌用于防重提交
     * @return
     */
    @GetMapping("token")
    public JsonData getOrderToken() {
        long accountNo = LoginInterceptor.threadLocal.get(). getAccountNo();
        String token = CommonUtil.getStringNumRandom(32);

        String key = String.format(RedisKey.SUBMIT_ORDER_TOKEN_KEY, accountNo, token);

        // 令牌有效时间30分钟
        stringRedisTemplate.opsForValue().set(key, String.valueOf(Thread.currentThread().getId()), 30, TimeUnit.MINUTES);

        return JsonData.buildSuccess(token);
    }

    /**
     * 查询订单状态
     * @param outTradeNo
     * @return
     */
    @GetMapping("query_state")
    public JsonData queryState(@RequestParam(value = "out_trade_no") String outTradeNo){
        String res = productOrderService.queryProductOrderState(outTradeNo);
        return StringUtils.isBlank(res) ? JsonData.buildResult(BizCodeEnum.ORDER_CONFIRM_NOT_EXIST) : JsonData.buildSuccess(res);
    }

    /**
     * 下单接口
     * @param orderRequest
     * @param response
     */
    @PostMapping("confirmOrder")
    public void confirmOrder (@RequestBody ConfirmOrderRequest orderRequest, HttpServletResponse response) {
        JsonData jsonData = productOrderService.confirmOrder(orderRequest);
        if (jsonData.getCode() == JsonCodeEnum.SUCCESS.getCode()) {
            // 端类型
            String clinetType = orderRequest.getClinetType();
            // 支付类型
            String payType = orderRequest.getPayType();

            if(payType.equalsIgnoreCase(ProductOrderEnum.ALI_PAY.name())) {
                // 如果是支付宝支付，跳转支付网页,sdk除外
                if (clinetType.equalsIgnoreCase(ProductOrderEnum.PC.name())) {
                    // PC端相应HTML
                    CommonUtil.sendHtmlMessage(response, jsonData);
                } else if (clinetType.equalsIgnoreCase(ProductOrderEnum.APP.name())) {
                    // APP支付
                } else if (clinetType.equalsIgnoreCase(ProductOrderEnum.H5.name())) {

                }
            } else if (payType.equalsIgnoreCase(ProductOrderEnum.WECHAT_PAY.name())) {
                // 微信支付,微信支付直接返回前端JSON数据即可
                CommonUtil.sendJsonMessage(response, jsonData);
            }
        } else {
            log.error("创建订单失败{}", jsonData);
            CommonUtil.sendJsonMessage(response, jsonData);
        }
    }
}

